import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { jwtConstants } from './constants';
import { InjectRepository } from '@nestjs/typeorm';
import { Villager } from 'libs/db/entity/villager.entity';
import { Repository } from 'typeorm';

@Injectable()
export class JwtForWebStrategy extends PassportStrategy(Strategy, 'jwt-web') {
  constructor(@InjectRepository(Villager) private readonly villagerRepo : Repository<Villager>) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey:  jwtConstants.secret,
    });
  }

  async validate(villager: any | Villager) {
    // return await this.villagerRepo
    //                 // .leftJoinAndSelect("villager.village", "village")
    //                 // .leftJoinAndSelect("villager.group", "group")
    //                 .findOne(villager.id)
    return  this.villagerRepo
      .createQueryBuilder('villager')
      .leftJoinAndSelect("villager.village", "village")
      .leftJoinAndSelect("villager.group", "group")
      .where('villager.id = :id', { id : villager.id })
      .getOne();
  }
}
